package com.example.dishchickenimageloader;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class BitmapHttpUtil {
    public static void getBitmap(final String url,final BitmapCallbackListener listener) {
        new Thread(() -> {
            Bitmap bitmap;
            URL imageURL;
            HttpURLConnection conn = null;

            try {
                imageURL = new URL(url);
                conn = (HttpURLConnection) imageURL.openConnection();
                conn.setDoInput(true);
                conn.connect();

                InputStream is = conn.getInputStream();
                bitmap = BitmapFactory.decodeStream(is);
                is.close();

                if (listener != null){
                    listener.onFinish(bitmap);
                }
            } catch (IOException e) {
                if (listener != null) {
                    listener.onError(e);
                }
            } finally {
                if (conn != null)
                    conn.disconnect();
            }

        }).start();

    }
}
